<template>
    <div class="search-container">
         <el-input
        v-model="filterParams.keyword"
        placeholder="请输入体检数值"
        style="width: 200px"
        class="filter-item"
        clearable
        @change="emitFilterChange"
      />
      <el-select
        v-model="filterParams.category"
        placeholder="指标分类"
        clearable
        class="filter-item"
        style="width: 150px"
        @change="emitFilterChange"
      >
        <el-option
          v-for="item in categoryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="filterParams.year"
        type="year"
        placeholder="选择年份"
        class="filter-item"
        style="width: 200px;margin-right: 20px;"
        @change="emitFilterChange"
      />
      <el-button
            class="filter-item"
            type="primary"
            :icon="Plus"
            @click="handleCreate"
          >
           新增
          </el-button>
          <el-button
            class="filter-item"
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            搜索
          </el-button>
    </div>
    <el-table
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="体检数值" prop="name" min-width="100" />
      <el-table-column label="指标分类" prop="category"min-width="100"  />
      <el-table-column label="年份" prop="year" min-width="100"  align="center" />
      <el-table-column label="公式" prop="formula" min-width="180"  >
        <template #default="{ row }">
          {{ formulaOptions.find(item => item.id === row.formula)?.name }}
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description" min-width="300" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            :icon="Edit"
            @click="handleEdit(row)"
          />
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="pagination.total"
      :page-size="pagination.pageSize"
      :current-page="pagination.currentPage"
      @update:current-page="handleCurrentChange"
      @update:page-size="handlePageSizeChange"
    />

    <el-dialog v-model="dialogVisible" :title="title" width="30%" :close-on-click-modal="false">
            <el-form :model="form" ref="formRef" label-width="80px" :rules="rules">
                <el-form-item label="数值" prop="name">
                    <el-input v-model="form.name" clearable placeholder="请输入数值"/>
                </el-form-item> 
                <el-form-item label="指标分类" prop="category">
                    <el-select v-model="form.category" placeholder="请选择指标分类" clearable>
                        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="指标公式" prop="formula">
                    <el-select v-model="form.formula" placeholder="请选择指标公式" clearable>
                        <el-option v-for="item in formulaOptions" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="年份" prop="year">
                    <el-date-picker v-model="form.year" type="year" placeholder="选择年份" style="width: 100%" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="form.description" clearable type="textarea" :rows="3"/>
                </el-form-item>
            </el-form>
            <template #footer>  
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">保存</el-button>
            </template>
        </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive } from 'vue'
  import Pagination from '@/components/Pagination/index.vue'
  import { Delete, Edit,Plus,Search } from '@element-plus/icons-vue'
  import { useIndicatorStore } from "@/stores/indicator"

  const indicatorStore = useIndicatorStore()  
  
  const filterParams = reactive({
    keyword: '',
    category: '',
    year: ''
  })
  
  const categoryOptions = indicatorStore.getIndicatorList.map(item => ({
    value: item.name,
    label: item.name
  }))

  const dialogVisible = ref(false)
  const form = ref({
    id: undefined,
    name: '',
    category: '',
    year: '',
    formula: '',
    description: ''
  })

  const rules = reactive({
    name: [{ required: true, message: '请输入指标名称', trigger: 'blur' }],
    category: [{ required: true, message: '请选择指标分类', trigger: 'blur' }],
    year: [{ required: true, message: '请选择年份', trigger: 'change' }],
    formula: [{ required: true, message: '请选择公式', trigger: 'blur' }]
  })
  
  const title = ref();
  const formRef = ref()

 
  const emit = defineEmits(['delete', 'edit'])
  
  interface IndicatorItem {
    id?: number
    name: string
    category: string
    year: string
    formula: number
    type: string
    description: string
  }

  const tableData = ref<IndicatorItem[]>([])
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  const formulaOptions = ref([
    {
        id: 1,
        name: '人口密度​',
        formula: 'total_population / total_area',
        description: '人口密度 = 城市总人口 / 城市面积'
    },
    {
        id: 2,
        name: '城市化率',  
        formula: ' city_population / total_population × 100%',
        description: '城市化率 = 城镇人口数 / 总人口数 × 100%'
    },
    {
        id: 3,
        name: '人均GDP​',
        formula: '(now_gdp - last_gdp) / last_gdp × 100%',
        description: 'GDP增长率 = [(当期GDP - 上期GDP) / 上期GDP] × 100%'
    },
  ])

  // 示例数据 - 实际应从API获取
  const mockData: IndicatorItem[] = [
    {
      id: 1,
      name: '100',
      category: '健康舒适',
      formula: 3,
      year: '2023',
      type: '导向指标',
      description: '市辖区建成内达到《完整居住社区建设标准（试行）》的居住社区数量，占居住社区总量的百分比'
    },
    {
      id: 2,
      name: '96',
      category: '交通便捷',
      formula: 2,
      year: '2022',
      type: '导向指标',
      description: '市辖区建成区内高峰期各类道路上各类机动车的平均速度'
    }
  ]

  const fetchData = async () => {
    console.log('fetchData')
    try {
      // 实际项目中调用API
      // const res = await getIndicatorList({ 
      //   page: pagination.currentPage,
      //   size: pagination.pageSize,
      //   year: filterParams.year,
      //   ...
      // })
      let filtered = mockData.filter(item => {
        let match = true
        if (filterParams.keyword) match = match && item.name.includes(filterParams.keyword)
        if (filterParams.category) match = match && item.category === filterParams.category
        if (filterParams.year) match = match && item.year === String(filterParams.year)
        return match
      })
      tableData.value = filtered as any
      pagination.total = filtered.length
    } catch (error) {
      console.error('获取数据失败:', error)
    }
  }

  const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    fetchData()
  }

  const handlePageSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchData()
  }


  const emitFilterChange = () => {
    console.log('筛选条件变更:', filterParams)
    fetchData()
  }

  const handleCreate = () => {
    dialogVisible.value = true
    title.value = '新增'
    formRef.value.resetFields()
    form.value = {
      id: undefined,
      name: '',
      category: '',
      year: '',
      formula: '',
      description: ''
    }
  }
  const handleAdd = () => {
    dialogVisible.value = false
    if(title.value === '新增'){
        // 自动生成id
        form.value.id = Date.now() as any
        tableData.value.push({ ...(form.value as any) })
    }else{
        tableData.value = tableData.value.map((item: IndicatorItem) => item.id === form?.value?.id ? { ...(form.value as any) } : item) as any
    }
    fetchData()
  }


  const handleDelete = (row: IndicatorItem) => {
    console.log('删除指标', row);
    tableData.value = tableData.value.filter((item: IndicatorItem) => item.id !== row.id)
    fetchData()
  }

  const handleEdit = (row: IndicatorItem) => {
    console.log('编辑指标', row)
    title.value = '编辑'
    dialogVisible.value = true
    form.value = JSON.parse(JSON.stringify(row))
  }

  const handleSearch = () => {
    console.log('搜索指标')
    fetchData()
  }

  defineExpose({
    fetchData
  })

  fetchData()
</script>
<style scoped lang="scss">
.search-container {
     margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
    }
}
</style>